package com.ccrfid.rmc6.util;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Date;

public class ImageCutter2 {
    public static void main(String[] args) throws IOException {
        String srcfile = "C:\\Users\\zhrq\\Desktop\\map\\huangzhou\\entity\\1-1.png";
        String destdir = "C:\\Users\\zhrq\\Desktop\\map\\huangzhou\\entity\\1-1\\";
        String suffix = srcfile.substring(srcfile.lastIndexOf(".") + 1);

        BufferedImage source = ImageIO.read(new File(srcfile));

        int max_x = maxN(source.getWidth());
        int max_y = maxN(source.getHeight());
        int sum = 0;
        for (int x = 0; x <= max_x; x++) {
            for (int y = 0; y <= max_y; y++) {
                long start = new Date().getTime();

                BufferedImage rect = source.getSubimage(x * 256, y * 256, 256, 256);
                String tilefile = destdir + "Y" + y + "_X" + x + "." + suffix;
                ImageIO.write(rect, suffix, new File(tilefile));

                long cost = new Date().getTime() - start;
                System.out.println("-- create tile: " + tilefile + ", cost " + cost + " ms");
                sum += cost;
            }
        }
        System.out.println("-- all run " + sum + " ms");
    }

    private static int maxN(int n) {
        if (n > 0) {
            int result = n / 256;
            int remainder = n % 256;
            if (remainder > 0) {
                return result;
            } else {
                return result - 1;
            }
        } else {
            return 0;
        }
    }
}
